// src/RecipeList.tsx
import React, { useState, useEffect } from 'react';
import { Layout, Card, Row, Col, Spin, message, Button, Select } from 'antd';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import Sidebar from './Sidebar';

const { Content } = Layout;
const { Option } = Select;

interface Recipe {
  id: string;
  title: string;
  coverImage: string;
  difficulty: number;
  difficultyAvg: number;
  userId: number;
  createdAt: string;
  updatedAt: string;
  category?: string;
  tags?: string[];
  description?: string;
}

const RecipeList: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { tag, category } = useParams<{ tag?: string; category?: string }>();

  const [recipes, setRecipes] = useState<Recipe[]>([]);
  const [filteredRecipes, setFilteredRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [keyword, setKeyword] = useState<string>('');
  const [type, setType] = useState<'tag' | 'category'>('tag');
  const [sortOrder, setSortOrder] = useState<string>('default');

  // 颜色配置 - 与Community界面完全一致
  const colorConfig = {
    primary: '#e8d9c7', // 主色调 - 浅棕色
    primaryDark: '#8b4513', // 深棕色 - 文字颜色
    border: '#d4b896', // 边框色
    background: '#f8f4f0', // 背景色
    badge: '#a0522d', // 徽章颜色
    tabActive: '#e8d9c7', // 标签页激活颜色
  };

  // 排序逻辑
  useEffect(() => {
    let sorted = [...recipes];
    if (sortOrder === 'difficulty') {
      sorted.sort((a, b) => a.difficulty - b.difficulty);
    } else if (sortOrder === 'rating') {
      sorted.sort((a, b) => b.difficultyAvg - a.difficultyAvg);
    }
    setFilteredRecipes(sorted);
  }, [recipes, sortOrder]);

  // 判断当前路由类型
  useEffect(() => {
    const isTagRoute = location.pathname.startsWith('/tag/');
    const isCategoryRoute = location.pathname.startsWith('/category/');

    if (isTagRoute && tag) {
      setKeyword(tag);
      setType('tag');
    } else if (isCategoryRoute && category) {
      setKeyword(category);
      setType('category');
    } else {
      message.error('无效的页面路径');
      navigate('/home');
    }
  }, [location.pathname, tag, category, navigate]);

  // 加载菜谱数据
  useEffect(() => {
    if (!keyword) return;

    const fetchData = async () => {
      setLoading(true);
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          message.error('请先登录');
          navigate('/login');
          return;
        }

        let queryParams = '';
        if (type === 'tag') {
          queryParams = `tag=${encodeURIComponent(keyword)}`;
        } else if (type === 'category') {
          queryParams = `category=${encodeURIComponent(keyword)}`;
        }

        const response = await fetch(`/api/recipe/search?${queryParams}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          const errorText = await response.text();
          console.error('后端返回错误:', errorText);
          message.error(`加载失败：${response.status} ${response.statusText}`);
          return;
        }

        const result = await response.json();

        if (Array.isArray(result)) {
          setRecipes(result);
        } else {
          console.warn('响应不是数组:', result);
          setRecipes([]);
        }
      } catch (error) {
        console.error('网络请求失败:', error);
        message.error('网络异常，请检查后端是否运行');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [keyword, type, navigate]);

  const getTitle = () => {
    return type === 'tag' ? `"${keyword}" 相关菜谱` : `"${keyword}" 菜系`;
  };

  // 返回按钮处理函数 - 与Community界面保持一致
  const handleBack = () => {
    navigate(-1);
  };

  const handleSortChange = (value: string) => {
    setSortOrder(value);
  };

  // 处理图片URL
  const processImageUrl = (imagePath: string): string => {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    if (imagePath.startsWith('/')) {
      return `http://218.244.141.86:8080${imagePath}`;
    }
    return `http://218.244.141.86:8080/${imagePath}`;
  };

  return (
    <Layout style={{ 
      minHeight: '100vh', 
      backgroundImage: "url('/background2.jpg')",
      backgroundSize: 'cover',
      backgroundPosition: 'center',
    }}>
      <Sidebar />
      
      <Layout style={{ background: 'transparent' }}>
        {/* 头部 - 与Community界面相同的样式 */}
        <div
          style={{
            padding: '20px 40px',
            background: 'white',
            boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
            borderRadius: '12px 12px 0 0',
            margin: '20px 40px 0 40px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            flexWrap: 'wrap',
            gap: '16px',
          }}
        >
          <h2 style={{ 
            margin: 0, 
            fontSize: '24px', 
            fontWeight: 'bold',
            color: colorConfig.primaryDark
          }}>
            {getTitle()}
          </h2>

          <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
            <span style={{ color: colorConfig.primaryDark }}>排序：</span>
            <Select
              value={sortOrder}
              onChange={handleSortChange}
              style={{ width: 160 }}
              size="small"
            >
              <Option value="default">默认</Option>
              <Option value="difficulty">难度（低→高）</Option>
              <Option value="rating">评分（高→低）</Option>
            </Select>
            
            {/* 返回按钮 - 与Community界面完全一致 */}
            <Button 
              icon={<ArrowLeftOutlined />}
              onClick={handleBack}
              style={{
                borderRadius: '20px',
                fontWeight: 'bold',
                borderColor: colorConfig.border,
                color: colorConfig.primaryDark,
                padding: '8px 20px',
                height: 'auto',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                whiteSpace: 'nowrap'
              }}
            >
              返回
            </Button>
          </div>
        </div>

        <Content
          style={{
            margin: '0 40px 20px 40px',
            padding: '0',
            background: 'transparent',
            borderRadius: '0 0 12px 12px',
          }}
        >
          <div
            style={{
              background: 'white',
              padding: '30px',
              borderRadius: '0 0 12px 12px',
              minHeight: 'calc(100vh - 200px)',
            }}
          >
            {loading ? (
              <div style={{ 
                textAlign: 'center', 
                paddingTop: '60px' 
              }}>
                <Spin size="large" style={{ color: colorConfig.primary }} />
                <p style={{ 
                  marginTop: 16, 
                  color: colorConfig.primaryDark 
                }}>
                  正在加载菜谱...
                </p>
              </div>
            ) : filteredRecipes.length > 0 ? (
              <Row gutter={[24, 24]} justify="center">
                {filteredRecipes.map((recipe) => (
                  <Col key={recipe.id} xs={12} sm={8} md={6} lg={6}>
                    <Card
                      hoverable
                      style={{
                        textAlign: 'center',
                        backgroundColor: 'rgba(255, 255, 255, 0.85)',
                        borderRadius: '12px',
                        border: '1px solid #e8d5b5',
                        padding: '20px',
                        backdropFilter: 'blur(8px)',
                        boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                        transition: 'all 0.3s ease',
                        cursor: 'pointer',
                      }}
                      bodyStyle={{ padding: '16px' }}
                      onClick={() => navigate(`/recipe/${recipe.id}`, { state: { recipe } })}
                    >
                      <img
                        src={processImageUrl(recipe.coverImage)}
                        alt={recipe.title}
                        style={{
                          width: '100%',
                          height: '160px',
                          objectFit: 'cover',
                          borderRadius: '8px',
                          marginBottom: '12px',
                        }}
                        onError={(e) => {
                            e.currentTarget.src = 'https://via.placeholder.com/300x200?text=无图';
                        }}
                      />
                      <div style={{ 
                        fontSize: '16px', 
                        fontWeight: 'bold', 
                        color: colorConfig.primaryDark,
                        marginBottom: '8px'
                      }}>
                        {recipe.title}
                      </div>
                      <div style={{ 
                        fontSize: '12px', 
                        color: '#666', 
                      }}>
                        难度: {recipe.difficulty}/5 · 评分: {recipe.difficultyAvg.toFixed(2)}
                      </div>
                    </Card>
                  </Col>
                ))}
              </Row>
            ) : (
              <div
                style={{
                  textAlign: 'center',
                  padding: '60px',
                  color: colorConfig.primaryDark,
                  background: 'rgba(255, 253, 248, 0.7)',
                  borderRadius: '12px',
                  marginTop: '20px',
                  opacity: 0.7
                }}
              >
                暂无"{keyword}"相关的菜谱
              </div>
            )}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default RecipeList;